package com.qf.blog.dao.impl;

import com.qf.blog.core.utils.DataSourceUtils;
import com.qf.blog.dao.ISystemUserDao;
import com.qf.blog.entity.SystemUser;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.Date;
import java.util.List;

public class SystemUserDaoImpl implements ISystemUserDao {

    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

    @Override
    public Integer insert(SystemUser systemUser) throws Exception {
        systemUser.setStatus(0); // 默认值是0
        systemUser.setCreateTime(new Date());
        String sql = "insert into t_system_user (username,password,sex,email,createTime,birthday,status) value(?,?,?,?,?,?,?)";
        return queryRunner.update(sql, systemUser.getUsername(), systemUser.getPassword(), systemUser.getSex(), systemUser.getEmail(), systemUser.getCreateTime(), systemUser.getBirthday(), systemUser.getStatus());
    }

    @Override
    public SystemUser selectById(Integer id) throws Exception {
        String sql = "select * from t_system_user where id = ?";
        return queryRunner.query(sql, new BeanHandler<SystemUser>(SystemUser.class), id);
    }

    @Override
    public Integer updateById(SystemUser systemUser) throws Exception {
        String sql = "update t_system_user set username = ?,password = ?,sex = ?,email = ?,birthday = ? where id = ?";
        return queryRunner.update(sql, systemUser.getUsername(), systemUser.getPassword(), systemUser.getSex(), systemUser.getEmail(), systemUser.getBirthday(), systemUser.getId());
    }

    @Override
    public Integer deleteById(Integer id) throws Exception {
        String sql = "update t_system_user set status = ? where id = ? and status = 0";
        return queryRunner.update(sql, 1, id);
    }

    @Override
    public List<SystemUser> selectList() throws Exception {
        String sql = "select * from t_system_user where status = 0";
        return queryRunner.query(sql, new BeanListHandler<SystemUser>(SystemUser.class));
    }
}
